#!/usr/bin/python
# -*- coding:utf-8 -*-
__author__ = 'good'

from ..extensions import db, csrf
from werkzeug.utils import secure_filename
from flask import request, g, send_from_directory
from flask.ext.login import login_required
from config import ALLOWED_EXTENSIONS, UPLOAD_FOLDER, BASEDIR
import json
from datetime import datetime
from time import time
from ..models import Uploads

img = ['bmp', 'jpg', 'png', 'gif', 'jpeg']
file = ['txt', 'rar', 'zip', 'tar', 'word', 'xsl', 'xsls']


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@csrf.exempt
@login_required
def upload():
    if request.method == 'POST':
        datestr = str(int(time()))
        file = request.files.get('imgFile', None)
        article_id = request.headers['Referer'].split('_')[-1]
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            fileType = filename.split('.')[-1]
            if fileType in img:
                savename = 'img' + datestr + '.' + fileType
                fileurl = '/img/' + savename
                fileType = 'img'
            else:
                savename = 'att' + datestr + '.' + fileType
                fileurl = '/att/' + savename
                fileType = 'att'
            try:
                file.save(UPLOAD_FOLDER + fileurl)
                url = "/uploads/" + savename
                upd = Uploads(file_name=savename,
                              file_url=fileurl,
                              article_id=article_id,
                              file_type=fileType,
                              upload_user=g.user.id)
                upd.upload_date = datetime.now()
                db.session.add(upd)
                db.session.commit()
                data = {'error': 0, 'url': url}
                return json.dumps(data)
            except Exception, ex:
                data = {'error': 1, 'message': 'Exception:%s' % (ex)}
                return json.dumps(data)
        else:
            data = {'error': 1, 'message': u'不支持的文件类型'}
            return json.dumps(data)
    return json.dumps({'error': 1, 'message': u'未知错误，请联系作者'})


def uploaded_file(filename):
    fileurl = filename[:3] + '/' + filename
    return send_from_directory(UPLOAD_FOLDER, fileurl)


def favicon_ico():  #
    return send_from_directory(BASEDIR, 'golsee/static/images/favicon.ico')


def robot_txt():  #
    return send_from_directory(BASEDIR, 'golsee/static/robot.txt')
